<template>
  <Modal v-model:visible="visible" :title="title" @cancel="close">
    <template #footer>
      <Button key="submit" type="primary" @click="submit">确认</Button>
      <Button key="back" @click="close">返回</Button>
    </template>
    <Form :model="formState" v-bind="formItemLayout" ref="formRef">
      <FormItem
        label="用户姓名"
        name="name"
        :rules="[{ required: true, message: title == '编辑' ? '请输入用户名' : '请选择用户' }]"
      >
        <Input v-if="title == '编辑'" v-model:value="formState.name"></Input>
        <Select v-if="title == '添加用户'" v-model:value="formState.name" :options="userList" label-in-value></Select>
      </FormItem>
      <FormItem label="邮箱" name="email" :rules="[{ required: true, message: '请输入邮箱' }]">
        <Input v-model:value="formState.email"></Input>
      </FormItem>
    </Form>
  </Modal>
</template>
<script lang="ts" setup>
import { Modal, Form, FormItem, Input, message, Button, Select } from 'ant-design-vue';
import { reactive, ref } from 'vue';
import { EditParams } from '/@/api/work-order/userManagement/user/model/userModel';
import { createUser, editUser } from '/@/api/work-order/userManagement/user/user';
const visible = ref(false);
const title = ref('添加用户');
let formState = reactive({} as EditParams);
const formRef = ref();

const openEdit = (record) => {
  title.value = '编辑';
  formState.email = record.email;
  formState.id = record.id;
  formState.name = record.name;
  visible.value = true;
};

const userList = ref();

// userList.value = await getUserList();
const openCreate = async () => {
  title.value = '添加用户';

  userList.value = [{ label: 'aaa', value: 123 }];
  visible.value = true;
};
const emit = defineEmits(['submitSuccess']);
const submit = async () => {
  if (title.value == '编辑') {
    formRef.value.validate().then(async () => {
      let res = await editUser(formState);
      if (res) {
        message.success('编辑成功');
      }
      emit('submitSuccess');
    });
  } else if (title.value == '添加用户') {
    let createParam = {
      email: formState.email,
      name: formState.name.label,
      userId: formState.name.value,
    };
    formRef.value.validate().then(async () => {
      let res = await createUser(createParam);
      if (res) {
        message.success('添加成功');
      }
      emit('submitSuccess');
    });
  }
};
const close = () => {
  visible.value = false;
  formRef.value.clearValidate();
  formState.email = '';
  formState.name = '';
};
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 },
};
defineExpose({ openEdit, openCreate });
</script>
